//
//  ENSearchViewController.m
//  EverydayNews
//
//  Created by 李沛池 on 2017/8/10.
//  Copyright © 2017年 Godlike. All rights reserved.
//

#import "ENSearchViewController.h"
#import "ENInterface.h"
#import "SharesModel.h"
#import "ENSharesTableHeaderView.h"

@interface ENSearchViewController ()<
UISearchBarDelegate,
UITableViewDelegate,
UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
@property (weak, nonatomic) IBOutlet LPCTableView *tableView;
@property (weak, nonatomic) IBOutlet UITableView *tableViewHistory;

@end

@implementation ENSearchViewController
{
    NSMutableArray *_arrayHistory;
    NSMutableArray *_arrayShares;
    BOOL _currentSortUP;//YES UP NO Down
    LPCMBProgressHUD *_hud;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
//    self.navigationController.navigationBarHidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
//    self.navigationController.navigationBarHidden = NO;
}

- (void)initData
{
    [self configArrayHistoryWords];
    
    [_tableViewHistory reloadData];
}

- (void)configArrayHistoryWords
{
    //读取搜索历史
    _arrayHistory = [[NSMutableArray alloc] initWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"searchHistoryWords"]];
    if (_arrayHistory.count == 0 && [[NSUserDefaults standardUserDefaults] boolForKey:@"isFirstSearch"]) {
        //保存默认数据
        for (NSString *word in @[@"财经",@"002739"]) {
            [self saveSHWord:word];
        }
        [_arrayHistory addObjectsFromArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"searchHistoryWords"]];
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isFirstSearch"];
    }
}

- (void)initUI
{
    [_searchBar becomeFirstResponder];
    
    [self configSearchBar];
    [self configTableViewHistory];
}

- (void)configSearchBar
{
    for(UIView *search in _searchBar.subviews )
    {
        NSMutableArray *array = [search valueForKeyPath:@"subviewCache"];
        for (id button in array) {
            if ([button isKindOfClass:[UIButton class]]) {
                UIButton *cancel = (UIButton *)button;
                [cancel setTitle:@"取消" forState:UIControlStateNormal];
                [cancel setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
            }
        }
    }
}

- (void)configTableViewHistory
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 90)];
    view.backgroundColor = [UIColor clearColor];
    
    UIButton *cancleBtn = [[UIButton alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width/2-60, 30, 120, 35)];
    [cancleBtn setTitle:@"清除搜索历史" forState: UIControlStateNormal];
    cancleBtn.titleLabel.font = [UIFont systemFontOfSize:14.0];
    [cancleBtn setTitleColor:[UIColor colorWithRed:80/255.0 green:80/255.0 blue:80/255.0 alpha:1] forState:UIControlStateNormal];
    cancleBtn.layer.borderColor = [UIColor colorWithRed:80/255.0 green:80/255.0 blue:80/255.0 alpha:1].CGColor;
    cancleBtn.layer.cornerRadius = 3;
    cancleBtn.layer.borderWidth = 0.5;
    [view addSubview:cancleBtn];
    [cancleBtn addTarget:self action:@selector(clearAllHistory) forControlEvents:UIControlEventTouchUpInside];

    _tableViewHistory.tableFooterView = view;
}

- (void)updateUI
{
    
}


#pragma mark - Custom
//保存搜索历史
- (void)saveSHWord:(NSString *)word
{
    if (![LPCTools deptNumInputShouldNumber:word] && ![LPCTools isChinese:word] && ![LPCTools pureLetters:word]) {
        return;
    }
    
    NSMutableArray *arraySave = [[NSMutableArray alloc] init];
    [arraySave addObjectsFromArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"searchHistoryWords"]];
    
    NSString *regex = @"\\s*";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    if (![arraySave containsObject:word] && ![pred evaluateWithObject:word]) {
        [arraySave insertObject:word atIndex:0];
    }
    [[NSUserDefaults standardUserDefaults] setObject:arraySave forKey:@"searchHistoryWords"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)sortShares:(BOOL)isUP
{
    _currentSortUP = isUP;
    
    [_arrayShares sortUsingComparator:^NSComparisonResult(SharesModel *  _Nonnull obj1, SharesModel *  _Nonnull obj2) {
        if ([obj1.diff_rate floatValue] > [obj2.diff_rate floatValue]) {
            return isUP==YES?NSOrderedDescending:NSOrderedAscending;
        }else if ([obj1.diff_rate floatValue] < [obj2.diff_rate floatValue]) {
            return isUP==YES?NSOrderedAscending:NSOrderedDescending;
        }else {
            
        }
        return NSOrderedSame;
    }];
}


#pragma mark - Action
//删除指定记录
- (void)removeWordIndex:(NSInteger)row
{
    NSMutableArray *arraySave = [[NSMutableArray alloc] initWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"searchHistoryWords"]];
    if (arraySave.count > row) {
        [arraySave removeObjectAtIndex:row];
    }
    [[NSUserDefaults standardUserDefaults] setObject:arraySave forKey:@"searchHistoryWords"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    [self configArrayHistoryWords];
    
    [_tableViewHistory reloadData];
}

//清空搜索记录
- (void)clearAllHistory
{
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"searchHistoryWords"];
    
    [self configArrayHistoryWords];
    
    [_tableViewHistory reloadData];
}


#pragma mark - UISearchBarDelegate
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    DissmissVC;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
    
    //保存进搜索历史
    [self saveSHWord:searchBar.text];
    
    [self searchShare:searchBar.text];
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    [self configArrayHistoryWords];
    
    [_tableViewHistory reloadData];
    
    [self.view bringSubviewToFront:_tableViewHistory];
    
    return YES;
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == _tableView) {
        return _arrayShares.count;
    }else {
        return _arrayHistory.count + 1;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LPCTableViewCell *cell;
    if (tableView == _tableView) {
        cell = XIBcellFromMainBundle(@"ENSharesCell");
        [cell updateData:_arrayShares[indexPath.row]];
    }else {
        cell = XIBcellFromMainBundle(@"ENSearchHistoryCell");
        if (indexPath.row == 0) {
            [cell updateData:nil withObject:@(YES)];
        }else {
            [cell updateData:_arrayHistory[indexPath.row - 1] withObject:@(NO)];
        }
        //点击删除记录按钮
        cell.baseCellBlock = ^{
            [self removeWordIndex:indexPath.row - 1];
        };
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    if (tableView == _tableViewHistory && indexPath.row > 0) {
        [_searchBar resignFirstResponder];
        //保存进搜索历史
        [self saveSHWord:_arrayHistory[indexPath.row - 1]];
        [self searchShare:_arrayHistory[indexPath.row - 1]];
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (tableView == _tableViewHistory) {
        return nil;
    }
    ENSharesTableHeaderView *thView = XIBFromMainBundle(@"ENSharesTableHeaderView");
    [thView updateData:@(_currentSortUP)];
    thView.changeShowBlock = ^(BOOL isUP) {
        [self sortShares:isUP];
        [_tableView reloadData];
    };
    return thView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (tableView == _tableView) {
        return 34;
    }
    return CGFLOAT_MIN;
}


#pragma mark - Network
//搜索股票
- (void)searchShare:(NSString *)word
{
    _hud = [LPCMBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [ENInterface searchSharesListWithWord:word success:^(NSDictionary *jsonDic) {
        if ([jsonDic[@"showapi_res_body"][@"ret_code"] intValue] == -1) {
            [_hud hide];
            [LPCMBProgressHUD showErrorWithText:jsonDic[@"showapi_res_body"][@"remark"]];
            return ;
        }
        [_arrayShares removeAllObjects];
        _arrayShares = nil;
        _arrayShares = [SharesModel modelArrayFromJSONArray:jsonDic[@"showapi_res_body"][@"list"]];
        if (_arrayShares.count > 0) {
            [self requestSharesDetail];
        }else {
            [_hud hide];
            [LPCMBProgressHUD showErrorWithText:@"无搜索结果"];
        }
    } failure:^(NSError *error) {
        [_hud hide];
        if (error == nil) {
            [LPCMBProgressHUD showErrorWithText:@"请输入正确的股票代码/名称/拼音"];
        }
    }];
}

//股票具体数据
- (void)requestSharesDetail
{
    NSMutableString *stocks = [[NSMutableString alloc] init];
    for (SharesModel *sharesModel in _arrayShares) {
        [stocks appendFormat:@"%@%@,",sharesModel.market,sharesModel.code];
    }
    if (stocks.length > 1) {
        [stocks deleteCharactersInRange:NSMakeRange(stocks.length - 1, 1)];
    }
    [ENInterface getSharesDetailListWithStocks:stocks success:^(NSDictionary *jsonDic) {
        [_hud hide];
        if ([jsonDic[@"showapi_res_body"][@"ret_code"] intValue] == -1) {
            [LPCMBProgressHUD showErrorWithText:jsonDic[@"showapi_res_body"][@"remark"]];
            return ;
        }
        //列表数据
        NSArray *arrayDetailList = jsonDic[@"showapi_res_body"][@"list"];
        for (int i = 0; i < _arrayShares.count; i++) {
            SharesModel *sharesModel = _arrayShares[i];
            [sharesModel setValuesForKeysWithDictionary:arrayDetailList[i]];
        }
        [self sortShares:NO];
        GCD_MAIN(^{
            [_tableView reloadData];
            [self.view bringSubviewToFront:_tableView];
        });
    } failure:^(NSError *error) {
        [_hud hide];
    }];
}


@end
